use loco_rs::prelude::*;
use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

pub use super::_entities::order_payments::{self, ActiveModel, Entity, Model};

#[derive(Debug, Deserialize, Serialize)]
pub struct CreateParams {
    pub order_id: String,
    pub charge_id: String,
    pub amount: Decimal,
    pub handling_fee: Decimal,
    pub paid: i8,
    pub reference: Option<String>,
}

#[derive(Debug, Validate, Deserialize)]
pub struct Validator {
    #[validate(length(min = 1, message = "Order ID must not be empty."))]
    pub order_id: String,
    #[validate(length(min = 1, message = "Charge ID must not be empty."))]
    pub charge_id: String,
}

impl Validatable for ActiveModel {
    fn validator(&self) -> Box<dyn Validate> {
        Box::new(Validator {
            order_id: self.order_id.as_ref().to_owned(),
            charge_id: self.charge_id.as_ref().to_owned(),
        })
    }
}

#[async_trait::async_trait]
impl ActiveModelBehavior for super::_entities::order_payments::ActiveModel {
    async fn before_save<C>(self, _db: &C, insert: bool) -> Result<Self, DbErr>
    where
        C: ConnectionTrait,
    {
        self.validate()?;
        if insert {
            let mut this = self;
            this.id = ActiveValue::Set(Uuid::new_v4().to_string());
            Ok(this)
        } else {
            Ok(self)
        }
    }
}

impl Model {
    /// finds an order payment by the provided id
    ///
    /// # Errors
    ///
    /// When could not find order payment or DB query error
    pub async fn find_by_id(db: &DatabaseConnection, id: &str) -> ModelResult<Self> {
        let order_payment = order_payments::Entity::find()
            .filter(
                model::query::condition()
                    .eq(order_payments::Column::Id, id)
                    .build(),
            )
            .one(db)
            .await?;
        order_payment.ok_or_else(|| ModelError::EntityNotFound)
    }

    /// finds order payments by the provided order id
    ///
    /// # Errors
    ///
    /// When could not find order payments or DB query error
    pub async fn find_by_order_id(
        db: &DatabaseConnection,
        order_id: &str,
    ) -> ModelResult<Vec<Self>> {
        let order_payments = order_payments::Entity::find()
            .filter(
                model::query::condition()
                    .eq(order_payments::Column::OrderId, order_id)
                    .build(),
            )
            .all(db)
            .await?;
        Ok(order_payments)
    }

    /// Asynchronously creates an order payment and saves it to the database.
    ///
    /// # Errors
    ///
    /// When could not save the order payment into the DB
    pub async fn create(db: &DatabaseConnection, params: &CreateParams) -> ModelResult<Self> {
        let order_payment = order_payments::ActiveModel {
            order_id: ActiveValue::set(params.order_id.to_string()),
            charge_id: ActiveValue::set(params.charge_id.to_string()),
            amount: ActiveValue::set(params.amount),
            handling_fee: ActiveValue::set(params.handling_fee),
            paid: ActiveValue::set(params.paid),
            reference: ActiveValue::set(params.reference.clone()),
            ..Default::default()
        }
        .insert(db)
        .await?;

        Ok(order_payment)
    }
}

impl ActiveModel {
    /// Updates the order payment's paid status
    ///
    /// # Errors
    ///
    /// when has DB query error
    pub async fn update_paid_status(
        mut self,
        db: &DatabaseConnection,
        paid: bool,
    ) -> ModelResult<Model> {
        self.paid = ActiveValue::set(if paid { 1 } else { 0 });
        Ok(self.update(db).await?)
    }

    /// Updates the order payment's reference
    ///
    /// # Errors
    ///
    /// when has DB query error
    pub async fn update_reference(
        mut self,
        db: &DatabaseConnection,
        reference: Option<String>,
    ) -> ModelResult<Model> {
        self.reference = ActiveValue::set(reference);
        Ok(self.update(db).await?)
    }
}
